package com.luomu.base.biz.cookBook.address.impl;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.luomu.base.api.constant.BaseRspConstants;
import com.luomu.base.api.cookBook.address.bo.*;
import com.luomu.base.api.cookBook.address.contant.AreaEnum;
import com.luomu.base.api.cookBook.address.service.ExpressAddressService;
import com.luomu.base.api.utils.DateUtils;
import com.luomu.base.biz.cookBook.address.dao.TDictAddressJdMapper;
import com.luomu.base.biz.cookBook.address.util.AddressParse;
import jakarta.annotation.PostConstruct;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/expressAddressExcelService")
public class ExpressAddressServiceImpl implements ExpressAddressService {
    private final Logger log = LoggerFactory.getLogger(ExpressAddressServiceImpl.class);

    @Autowired
    private TDictAddressJdMapper tDictAddressJdMapper;

    /**
     * 省市区县数据文件路径（根据实际情况调整）
     */
    public static final String FILE_PATH = "/address-parse/china-area.json";


    /**
     * 初始化地址JSON
     */
    @Override
    @PostConstruct
    public CommonRspBO initAddressJson(){

        CommonRspBO rspBaseBO=new CommonRspBO();
        rspBaseBO.setCode(BaseRspConstants.RSP_CODE_SUCCESS);

        new Thread(() -> {
            Date start = new Date();
            log.info("----【初始化地址，开始时间】---：" + DateUtils.dateToStrLong(start));

            List<TDictAddressJdJson> addressJdPOS = tDictAddressJdMapper.queryAll();

            Date end = new Date();
            log.info("------【查询完成】-----：总耗时：" + (end.getTime() - start.getTime()) + "毫秒");


            Gson gson = new Gson();
            List<AreaTree> areas = gson.fromJson(gson.toJson(addressJdPOS), new TypeToken<List<AreaTree>>() {}.getType());
            Iterator<AreaTree> iterator = areas.iterator();
            while (iterator.hasNext()) {
                AreaTree next = iterator.next();
                if (AreaEnum.CITY.getCode().equals(next.getLevel()) || AreaEnum.DISTRICT.getCode().equals(next.getLevel())) {
                    if (StringUtils.length(next.getName()) <= 2) {
                        iterator.remove();
                    }
                    if (StringUtils.equals(next.getName(), "市辖区")) {
                        iterator.remove();
                    }
                }
            }

            areas = TreeUtils.buildPath(areas, o -> Objects.equals(o.getParentCode(), 0L));
            Map<Integer, List<AreaTree>> areaMapping = areas.stream().collect(Collectors.groupingBy(AreaTree::getLevel));

            AddressParse.addressParse(areaMapping);

            end = new Date();
            log.info("----【初始化地址，结束时间】---" + DateUtils.dateToStrLong(new Date()) + ",总耗时：" + (end.getTime() - start.getTime()) + "毫秒");

        }).start();


        return rspBaseBO;
    }


    /**
     * 初始化地址JSON-抄一个同步接口出来-jack.liu
     */
    @Override
    public CommonRspBO initAddressJsonNow(){
        CommonRspBO rspBaseBO=new CommonRspBO();
        Date start = new Date();
        log.info("----【初始化地址，开始时间】---：" + DateUtils.dateToStrLong(start));

        List<TDictAddressJdJson> addressJdPOS = tDictAddressJdMapper.queryAll();

        Date end = new Date();
        log.info("------【查询完成】-----：总耗时：" + (end.getTime() - start.getTime()) + "毫秒");


        Gson gson = new Gson();
        List<AreaTree> areas = gson.fromJson(gson.toJson(addressJdPOS), new TypeToken<List<AreaTree>>() {}.getType());
        Iterator<AreaTree> iterator = areas.iterator();
        while (iterator.hasNext()) {
            AreaTree next = iterator.next();
            if (AreaEnum.CITY.getCode().equals(next.getLevel()) || AreaEnum.DISTRICT.getCode().equals(next.getLevel())) {
                if (StringUtils.length(next.getName()) <= 2) {
                    iterator.remove();
                }
                if (StringUtils.equals(next.getName(), "市辖区")) {
                    iterator.remove();
                }
            }
        }

        areas = TreeUtils.buildPath(areas, o -> Objects.equals(o.getParentCode(), 0L));
        Map<Integer, List<AreaTree>> areaMapping = areas.stream().collect(Collectors.groupingBy(AreaTree::getLevel));

        AddressParse.addressParse(areaMapping);

        end = new Date();
        log.info("----【初始化地址，结束时间】---" + DateUtils.dateToStrLong(new Date()) + ",总耗时：" + (end.getTime() - start.getTime()) + "毫秒");
        rspBaseBO.setCode(BaseRspConstants.RSP_CODE_SUCCESS);
        return rspBaseBO;
    }

    @Override
    public ExpressParseAddressRspBO expressParseAddress(ExpressParseAddressReqBO req){
        ExpressParseAddressRspBO rsp=new ExpressParseAddressRspBO();
        String address = req.getAddress();

        log.info("-------------【入参address】-----------{}",address);

        ParseResult result = new ParseResult();
        try {
            result  = AddressParse.parseSingle(address, 1);
        } catch (Exception e){
            return rsp;
        }

        log.info("-------------【解析后的返参】-----------{}",JSON.toJSONString(result));

        if(result!=null){
            BeanUtils.copyProperties(result,rsp);
        }

        return rsp;
    }

}
